<?php

namespace app\util;

class Util
{
    // 微信支付时
    public static function getIp()
    {
        $cip = 'unknown';
        if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv('REMOTE_ADDR')) {
            $cip = getenv('REMOTE_ADDR');
        }

        return $cip;

        // if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        //     // 有反向代理
        //     return $_SERVER['HTTP_X_FORWARDED_FOR'];
        // }
        //
        // return $_SERVER['REMOTE_ADDR'];
    }

    /**
     * Get client ip address
     *
     * @return array|false|mixed|string
     */
    public static function getClientIp ()
    {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } else if (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } else if (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        return $ip;
    }

    /**
     * Generate nonce
     *
     * @param int $length
     * @return string
     */
    public static function generateNonceString($length = 32)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * Convert images in content
     *
     * @param $str
     * @return array|mixed
     */
    public static function convertImages($str)
    {
        // todo class="spsfsp"
        $pattern = "/<img (.*?) src=\"(.+?)\".*?>/";

        $list = [
            'images' => [],
            'text' => ''
        ];

        // query image
        preg_match_all($pattern, $str, $images);
        if (count($images) > 0) {
            $list['images'] = $images[2];
        }

        // replace text
        $list['text'] = preg_replace($pattern, '', $str);

        return $list;
    }
}